<template>
    <div class="share-popup">
        <popup
            ref="popupRef"
            title="分享至广场"
            :async="true"
            width="400px"
            customClass="!rounded-[20px]"
            :center="true"
            cancelButtonText=""
            confirmButtonText=""
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <div class="h-[160px]">
                <el-select
                    class="w-[360px]"
                    v-model="formData.categoryId"
                >
                    <el-option
                        v-for="item in cateLists"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </div>
            <div class="dialog-footer flex justify-center">
                <el-button
                    type="primary"
                    :loading="isLock"
                    @click="handleSubmit"
                >
                    分享至广场
                </el-button>
            </div>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import { getDrawSquareCateLists, shareDrawSquare } from '~/api/square'
import Popup from '~/components/popup/index.vue'
import { useLockFn } from '@/composables/useLockFn'

const emit = defineEmits(['success', 'close'])
const popupRef = shallowRef<InstanceType<typeof Popup>>()

const cateLists = ref<any[]>([])
const formData = reactive({
    is_base64: 0,
    base64: '',
    prompts: '',
    categoryId: '',
    drawRecordsId: ''
})

const getData = async () => {
    try {
        cateLists.value = await getDrawSquareCateLists()
    } catch (error) {
        console.log('获取绘画分类失败=>', error)
    }
}

//提交
const { lockFn: handleSubmit, isLock } = useLockFn(async (text: string) => {
    await shareDrawSquare(formData)
    feedback.msgSuccess('分享成功')
    popupRef.value?.close()
    emit('success')
})

const handleClose = () => {
    emit('close')
}

const open = (draw: any) => {
    getData()
    popupRef.value?.open()
    formData.base64 = draw.base64
    formData.is_base64 = draw.is_base64
    formData.prompts = draw.prompt_en || draw.prompt
    formData.drawRecordsId = draw.id
}

defineExpose({ open })
</script>
